'''
Created on Mar 23, 2011

@author: Mario
'''


from Bio import ExPASy
from Bio import SwissProt

def fetch(id):
    handle = ExPASy.get_sprot_raw(id)
    record = SwissProt.read(handle)
    return record.sequence
####

from Bio.Align.Applications import ClustalwCommandline
import re

def score(p1_str, p2_str):
    f = open(r'E:\workspace\Python\BioInfProject\src\mario_tmp\temp_protein_pair.faa','w')
    f.write('>P1\n')
    f.write(p1_str + '\n')
    f.write('>P2\n')
    f.write(p2_str + '\n')
    f.close()
    
    clustalw2 = r"C:\\Program Files\\ClustalW2\\clustalw2.exe";
    cline = ClustalwCommandline (clustalw2, infile = r"E:\workspace\Python\BioInfProject\src\mario_tmp\temp_protein_pair.faa", score="percent");
    output = cline()[0]

    #Vraca prvi rezultat sequence comparisona u %
    str1 = re.findall(r'Score:\s*\d+', output)[0]
    num = int(re.findall(r'\d+', str1)[0])
    return num
####

def create_fasta(graph, file):
    vs = graph.vs;
    i = 0;
    for v in vs :
        try:
            print v['uniprot_id'];
            prot2file(fetch(v['uniprot_id']), v['fullName'], i, file)
            i += 1;
        except ValueError:
            try:
                print v['uniprot_id'], " X";
                desc = re.split(" ", v['fullName'], 1000)
                prot2file(fetch(descriptive_id(desc[len(desc)-1])), v['fullName'], i, file)
                i += 1;
            except UnboundLocalError:
                print v['uniprot_id'], " X OBSOLETE";
                prot2file('', v['fullName'] + ' OBSOLETE', -1, file)
                #i += 1;
    return
####

def prot2file(prot, desc, pid, file):
    f = open(file, 'a');
    f.write('>P' + str(pid) + '     ' + desc + '\n');
    f.write(prot + '\n');
    f.close();
    return
####

import urllib

def descriptive_id(desc):
    handle = ExPASy.sprot_search_ful(desc)      #"heat shock protein 90 10116"
    result = handle.read()

    p = re.compile('(http.*score)\n', re.DOTALL)
    if "Status: 302" in result:
        url = re.findall(p, result)
        url = re.sub(' ', '%20', url[0])

    sock = urllib.urlopen(url)
    htmlSource = sock.read()
    sock.close()

    #ako ima addOrAppendCart, onda je nasao barem jedan rezultat
    p = re.compile('"addOrAppendCart\(\'([\w]{6})')
    if "addOrAppendCart" in htmlSource:
        target_id = re.findall(p, htmlSource)
    
    return target_id[0]          #trazeni rezultat
####

def evaluate_fastas(file1, file2):
#f1 = open('/Users/Mario/Documents/workspaceCPP/BIO_Projekt/working_data/Celeg20101010.faa', 'r');
#f2 = open('/Users/Mario/Documents/workspaceCPP/BIO_Projekt/working_data/Hpylo20101010.faa', 'r');
    
    f1 = open(file1, 'r');
    f2 = open(file2, 'r');
    
    s1 = f1.readlines()
    s2 = f2.readlines()
    
    print s1
    
    result = [];
    
    
    offset1 = 0; i = 0;
    while (i < (len(s1)/2)):
        if float(re.findall(">P(-*\d+) ", s1[2*i])[0]) == (-1):
            offset1 += 1;
            i+=1
        else :
            #print i-offset, s1[2*i +1]
            row = [];
            offset2 = 0; j = 0;
            while (j < (len(s2)/2)):
                if float(re.findall(">P(-*\d+) ", s2[2*j])[0]) == (-1):
                    offset2 += 1;
                    j+=1
                else:
                    #print j-offset2, s2[2*j +1]
                    row.append(score( s1[2*i +1], s2[2*j +1]))
                    j += 1;
            result.append(row);
            print result;
            i += 1;
    
    f = open('/Users/Mario/Documents/workspaceCPP/BIO_Projekt/working_data/result.txt', 'w');
    for res in result:
        f.write(str(res) + "\n");
####

def read_results(filename):
    #f = open('/Users/Mario/Documents/workspaceCPP/BIO_Projekt/working_data/result.txt', 'r');
    f = open(filename, 'r');

    matrix = []
    for line in f.readlines():
        line = line.lstrip('[')
        line = line.rstrip(']\n')
        line = line.split(', ')
        row = []
        for element in line:
            row.append(int(element))
        matrix.append(row)
    return matrix
####